﻿using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NopSolutions.NopCommerce.Controls
{

    public class GroupedRepeater : Repeater
    {
        private string _lastGroup;
        private string _groupColumn;
        private ITemplate _groupTemplate;
 
        /// <summary> 
        /// Gets or sets the column to group by.
        /// </summary> 
        [Browsable(true), Category("Behaviour")]
        public string GroupColumn
        {
            get { return _groupColumn; }
            set { _groupColumn = value; }
        }
 
        /// <summary> 
        /// Gets or sets the template used for Grouping.
        /// </summary> 
        [PersistenceMode(PersistenceMode.InnerProperty),Browsable(false),TemplateContainer(typeof(RepeaterItem)),DefaultValue("")]
        public virtual ITemplate GroupTemplate
        {
            get { return _groupTemplate; }
            set { _groupTemplate = value; }
        }
 
        /// <summary> 
        /// Default constructor.
        /// </summary> 
        public GroupedRepeater()
        {
            _lastGroup = null;
        }
 
        /// <summary> 
        /// Called when an item is created.
        /// </summary> 
        /// <param name="e"></param> 
        protected override void OnItemCreated(RepeaterItemEventArgs e)
        {
            base.OnItemCreated(e);
 
            if (!string.IsNullOrEmpty(GroupColumn))
            {
                string currentGroup = e.Item.DataItem.GetType().GetProperty(GroupColumn).GetValue(e.Item.DataItem, null).ToString();
                if (_lastGroup == null || _lastGroup != currentGroup)
                {
                    RepeaterItem item = new RepeaterItem(0, ListItemType.Item);
 
                    GroupTemplate.InstantiateIn(item);
                    item.DataItem = e.Item.DataItem;
                    this.Controls.Add(item);
                    item.DataBind();
 
                    _lastGroup = currentGroup;
                }
            }
        }
    }
}

